import { logger } from '@/utils/logger';

const DEEPSEEK_API_URL = 'https://api.deepseek.com/v1/chat/completions';
const DEEPSEEK_MODEL = 'deepseek-chat';

const PROMPT_INSTRUCTIONS = `You are an English grammar correction assistant.
Task: Correct the user's English text with minimal necessary edits (no stylistic over-correction).
Output strictly in this JSON schema:
{
  "corrected": "the corrected text",
  "issues": [
    {
      "type": "Grammar|Spelling|Punctuation|WordChoice|Style",
      "original": "original phrase (short)",
      "suggestion": "suggested fix (short)",
      "explanation": "brief explanation (<= 20 words)"
    }
  ]
}
Rules:
- Only minimal edits required to fix errors.
- Keep meaning intact, do not rewrite entire sentences unless necessary.
- Ensure valid JSON, no trailing commas, no extra commentary.
`;

export type GrammarIssue = {
  type: 'Grammar' | 'Spelling' | 'Punctuation' | 'WordChoice' | 'Style' | string;
  original: string;
  suggestion: string;
  explanation: string;
};

export type GrammarCheckResult = {
  corrected: string;
  issues: GrammarIssue[];
};

function stripCodeFence(content: string): string {
  let c = content.trim();
  if (c.startsWith('```')) {
    // remove leading ```[lang]
    c = c.replace(/^```[a-zA-Z]*\s*/, '');
    // remove trailing ```
    if (c.endsWith('```')) c = c.slice(0, -3);
    c = c.trim();
  }
  return c;
}

export async function callDeepseekGrammar(text: string, apiKey: string): Promise<GrammarCheckResult> {
  const payload = {
    model: DEEPSEEK_MODEL,
    messages: [
      { role: 'system', content: PROMPT_INSTRUCTIONS },
      { role: 'user', content: text },
    ],
    temperature: 0.2,
    response_format: { type: 'text' },
  };

  const resp = await fetch(DEEPSEEK_API_URL, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${apiKey}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(payload),
  });

  if (!resp.ok) {
    const body = await resp.text().catch(() => '');
    logger.error('DeepSeek API error', { status: resp.status, body });
    const bodySnippet = body ? body.slice(0, 500) : '';
    throw new Error(`DeepSeek API error: ${resp.status} ${bodySnippet}`);
  }

  const data: any = await resp.json().catch(() => ({}));
  let content = '';
  try {
    content = data?.choices?.[0]?.message?.content ?? '';
  } catch {
    content = '';
  }

  const result: GrammarCheckResult = { corrected: '', issues: [] };

  if (content) {
    const cleaned = stripCodeFence(content);
    try {
      const parsed = JSON.parse(cleaned);
      if (parsed && typeof parsed === 'object') {
        result.corrected = (parsed.corrected ?? '').toString();
        const issues = Array.isArray(parsed.issues) ? parsed.issues : [];
        result.issues = issues.slice(0, 50);
      } else {
        result.corrected = cleaned;
      }
    } catch {
      result.corrected = cleaned;
    }
  }

  if (!result.corrected) result.corrected = text;
  if (!Array.isArray(result.issues)) result.issues = [];

  return result;
}